<template>
  <div>
    <div>
      <input type="text" v-model="a">原始对象----- <input type="text" v-model="b">
      <br>
      <h4>
        {{addab}}
      </h4>
      <h5>
        第二种写法
        <br>
        {{addab1}}
      </h5>
      <hr>
      <p>购物车</p>
      <form action="">
        <table border>
          <thead>
            <tr align="center">
              <th>名称</th>
              <th>数量</th>
              <th>价格</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody v-for="item,index in data" :key="index">
            <tr>
              <td>{{item.name}}</td>
              <td><button @click="computer(index,false)">-</button><span>{{item.num}}</span><button @click="computer(index,true)">+</button></td>
              <td>{{item.price *item.num}}</td>
              <td>
                <button @click="del(index)">删除</button>
              </td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td>合计</td>
              <td colspan="3">{{$total}}元</td>
            </tr>
          </tfoot>
        </table>
      </form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
let a = ref("");
let b = ref("");
const addab = computed(() => {
  return a.value + "----" + b.value;
});

const addab1 = computed({
  get() {
    return a.value + "----" + b.value;
  },
  set() {
    return a.value + "----" + b.value;
  },
});

type Shop = {
  name: string;
  num: number;
  price: number;
};
const data = reactive<Shop[]>([
  {
    name: "abbs",
    num: 1,
    price: 100,
  },
  {
    name: "ck",
    num: 1,
    price: 235,
  },
  {
    name: "七匹狼",
    num: 1,
    price: 180,
  },
]);

const del = (index: number) => {
  data.splice(index, 1);
};
const computer = (index: number, flag: boolean) => {
  if (flag) {
    data[index].num++;
  } else {
    data[index].num > 0 ? data[index].num-- : data[index].num;
  }
};

let $total = computed<number>(() => {
  return data.reduce((prev, next) => {
    return prev + next.num * next.price;
  }, 0);
});
</script>

<style lang="less" scoped>
@border: #ccc;
table {
  text-align: center;
  min-width: 800px;
  border: 1px solid @border;
  th,
  td {
    text-align: center;
    line-height: 2;
    letter-spacing: 1px;
  }
  span {
    display: inline-block;
    padding: 0 5px 0;
    min-width: 20px;
  }
}
</style>